package com.szewec.ps.ui.road.facilities.intersection.task.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.szewec.ps.util.TextViewUtil;

public class ViewUtils {
    //触摸事件是否点击在v上
    public static boolean isClickNotInView(View v, MotionEvent event) {
        if ((v instanceof TextView)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    //获取文本框文本长度
    public static int getTextWidth(TextView textView) {
        if (textView == null) {
            return 0;
        }
        Rect bounds = new Rect();
        String text = textView.getText().toString();
        Paint paint = textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.left + bounds.width();
    }

    //监听滑动,滑动状态下让所有输入框失去焦点
    public static boolean dispatchTouchEvent(Activity activity, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = activity.getCurrentFocus();
            if (ViewUtils.isClickNotInView(v, event)) {//点击editText控件外部
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    TextViewUtil.closeKeyboard(activity);
                    v.clearFocus();
                }
            }
//            return activity.dispatchTouchEvent(event);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return activity.getWindow().superDispatchTouchEvent(event) || activity.onTouchEvent(event);
    }


}
